Skip to main content

features_cli/
http_server.rs

1//! HTTP server module for serving features data and embedded static files.
2//!
3//! This module provides functionality to start an HTTP server that serves:
4//! - Features data as JSON at `/features.json`
5//! - Embedded static files from the compiled binary
6//! - A default index page at the root path
7//!
8//! The server uses the `warp` web framework and supports CORS for cross-origin requests.
9//! Static files are embedded at compile time using the `include_dir` crate.
10
11use 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
25// Embed the public directory at compile time
26static STATIC_DIR: Dir<'_> = include_dir!("$CARGO_MANIFEST_DIR/public");
27
28/// Configuration for the HTTP server
29#[derive(Debug, Clone)]
30pub struct ServerConfig {
31    /// Port to run the server on
32    pub port: u16,
33    /// Host address to bind to
34    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    /// Create a new server configuration with custom port
48    pub fn new(port: u16) -> Self {
49        Self {
50            port,
51            ..Default::default()
52        }
53    }
54
55    /// Set the host address to bind to
56    #[allow(dead_code)]
57    pub fn with_host(mut self, host: [u8; 4]) -> Self {
58        self.host = host;
59        self
60    }
61}
62
63/// Starts an HTTP server with file watching for a specific directory.
64///
65/// # Arguments
66///
67/// * `features` - Initial Feature objects to serve as JSON
68/// * `port` - Port number to run the server on
69/// * `watch_path` - Path to watch for file changes
70/// * `on_ready` - Optional callback to be called when server is ready
71/// * `skip_changes` - Whether changes were skipped during feature computation
72/// * `ignore_paths` - Folders to ignore when features are recomputed
73/// * `include_skipped_dirs` - Whether to scan folders skipped by default when features are recomputed
74///
75/// # Returns
76///
77/// * `Result<()>` - Ok if server starts successfully, Err otherwise
78pub 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
100/// Starts an HTTP server with custom configuration and optional file watching.
101///
102/// # Arguments
103///
104/// * `features` - Slice of Feature objects to serve as JSON
105/// * `config` - Server configuration
106/// * `watch_path` - Optional path to watch for file changes
107/// * `on_ready` - Optional callback to be called when server is ready
108/// * `skip_changes` - Whether changes were skipped during feature computation
109/// * `ignore_paths` - Folders to ignore when features are recomputed
110/// * `include_skipped_dirs` - Whether to scan folders skipped by default when features are recomputed
111///
112/// # Returns
113///
114/// * `Result<()>` - Ok if server starts successfully, Err otherwise
115pub 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    // Create shared state for features
125    let features_data = Arc::new(RwLock::new(features.to_vec()));
126
127    // Get repository URL from git config
128    let repository_url = watch_path
129        .as_ref()
130        .and_then(|path| get_repository_url(path));
131
132    // Set up file watching if watch_path is provided
133    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    // Route for features.json with shared state
152    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    // Route for metadata.json with version info and repository URL
176    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                // Add repository URL if available
187                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    // Route for root path to serve index.html
208    let index_route = warp::path::end().and(warp::get()).and_then(serve_index);
209
210    // Route for static files from embedded directory
211    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    // Call the ready callback if provided
223    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
242/// Sets up file system watching for the specified path.
243async 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    // Set up the file watcher in a blocking task
252    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                        // Send event through channel
259                        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    // Process file system events
275    while let Some(event) = rx.recv().await {
276        // Check if this is a file we care about (README.md files or directory changes)
277        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            // Add a small delay to avoid excessive recomputation during rapid changes
287            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/// Custom error type for serialization failures
310#[derive(Debug)]
311struct SerializationError;
312impl warp::reject::Reject for SerializationError {}
313
314/// Serves the index page for the root path.
315///
316/// If embedded `index.html` exists, it will be served. Otherwise, a default
317/// HTML page with navigation links will be returned.
318///
319/// # Returns
320///
321/// * `Result<impl warp::Reply, warp::Rejection>` - HTML response or rejection
322async 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
338/// Serves static files from the embedded directory.
339///
340/// # Arguments
341///
342/// * `path` - The requested file path
343///
344/// # Returns
345///
346/// * `Result<impl warp::Reply, warp::Rejection>` - File content or rejection
347async fn serve_static_file(path: warp::path::Tail) -> Result<impl warp::Reply, warp::Rejection> {
348    let path_str = path.as_str();
349
350    // Try to get the file from the embedded directory
351    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            // Text file
356            Ok(warp::reply::with_header(contents, "content-type", content_type).into_response())
357        } else {
358            // Binary file
359            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
369/// Determines the content type based on file extension.
370///
371/// # Arguments
372///
373/// * `path` - The file path
374///
375/// # Returns
376///
377/// * `&'static str` - The appropriate MIME type
378fn 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
405/// Creates the default HTML page when no index.html is found.
406fn 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
456/// Handles HTTP request rejections and converts them to appropriate responses.
457async 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}