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///
73/// # Returns
74///
75/// * `Result<()>` - Ok if server starts successfully, Err otherwise
76pub async fn serve_features_with_watching(
77    features: &[Feature],
78    port: u16,
79    watch_path: PathBuf,
80    on_ready: Option<Box<dyn FnOnce() + Send>>,
81    skip_changes: bool,
82    ignore_paths: Vec<PathBuf>,
83) -> Result<()> {
84    let config = ServerConfig::new(port);
85    serve_features_with_config_and_watching(
86        features,
87        config,
88        Some(watch_path.clone()),
89        on_ready,
90        skip_changes,
91        ignore_paths,
92    )
93    .await
94}
95
96/// Starts an HTTP server with custom configuration and optional file watching.
97///
98/// # Arguments
99///
100/// * `features` - Slice of Feature objects to serve as JSON
101/// * `config` - Server configuration
102/// * `watch_path` - Optional path to watch for file changes
103/// * `on_ready` - Optional callback to be called when server is ready
104/// * `skip_changes` - Whether changes were skipped during feature computation
105///
106/// # Returns
107///
108/// * `Result<()>` - Ok if server starts successfully, Err otherwise
109pub async fn serve_features_with_config_and_watching(
110    features: &[Feature],
111    config: ServerConfig,
112    watch_path: Option<PathBuf>,
113    on_ready: Option<Box<dyn FnOnce() + Send>>,
114    skip_changes: bool,
115    ignore_paths: Vec<PathBuf>,
116) -> Result<()> {
117    // Create shared state for features
118    let features_data = Arc::new(RwLock::new(features.to_vec()));
119
120    // Get repository URL from git config
121    let repository_url = watch_path
122        .as_ref()
123        .and_then(|path| get_repository_url(path));
124
125    // Set up file watching if watch_path is provided
126    if let Some(ref path) = watch_path {
127        let features_data_clone = Arc::clone(&features_data);
128        let watch_path_clone = path.clone();
129
130        tokio::spawn(async move {
131            if let Err(e) =
132                setup_file_watcher(features_data_clone, watch_path_clone, ignore_paths).await
133            {
134                eprintln!("File watcher error: {}", e);
135            }
136        });
137    }
138
139    // Route for features.json with shared state
140    let features_data_clone = Arc::clone(&features_data);
141    let features_route = warp::path("features.json")
142        .and(warp::get())
143        .and_then(move || {
144            let features_data = Arc::clone(&features_data_clone);
145            async move {
146                let features = features_data.read().await;
147                let features_json = match serde_json::to_string_pretty(&*features) {
148                    Ok(json) => json,
149                    Err(e) => {
150                        eprintln!("Failed to serialize features: {}", e);
151                        return Err(warp::reject::custom(SerializationError));
152                    }
153                };
154
155                Ok::<_, warp::Rejection>(warp::reply::with_header(
156                    features_json,
157                    "content-type",
158                    "application/json",
159                ))
160            }
161        });
162
163    // Route for metadata.json with version info and repository URL
164    let metadata_route = warp::path("metadata.json")
165        .and(warp::get())
166        .and_then(move || {
167            let repo_url = repository_url.clone();
168            async move {
169                let mut metadata = serde_json::json!({
170                    "version": env!("CARGO_PKG_VERSION"),
171                    "skipChanges": skip_changes
172                });
173
174                // Add repository URL if available
175                if let Some(url) = repo_url {
176                    metadata["repository"] = serde_json::json!(url);
177                }
178
179                let metadata_json = match serde_json::to_string_pretty(&metadata) {
180                    Ok(json) => json,
181                    Err(e) => {
182                        eprintln!("Failed to serialize metadata: {}", e);
183                        return Err(warp::reject::custom(SerializationError));
184                    }
185                };
186
187                Ok::<_, warp::Rejection>(warp::reply::with_header(
188                    metadata_json,
189                    "content-type",
190                    "application/json",
191                ))
192            }
193        });
194
195    // Route for root path to serve index.html
196    let index_route = warp::path::end().and(warp::get()).and_then(serve_index);
197
198    // Route for static files from embedded directory
199    let static_route = warp::path::tail()
200        .and(warp::get())
201        .and_then(serve_static_file);
202
203    let routes = features_route
204        .or(metadata_route)
205        .or(index_route)
206        .or(static_route)
207        .with(warp::cors().allow_any_origin())
208        .recover(handle_rejection);
209
210    // Call the ready callback if provided
211    if let Some(callback) = on_ready {
212        callback();
213    }
214
215    println!(
216        "Server running at http://{}:{}",
217        config
218            .host
219            .iter()
220            .map(|&b| b.to_string())
221            .collect::<Vec<_>>()
222            .join("."),
223        config.port,
224    );
225    warp::serve(routes).run((config.host, config.port)).await;
226
227    Ok(())
228}
229
230/// Sets up file system watching for the specified path.
231async fn setup_file_watcher(
232    features_data: Arc<RwLock<Vec<Feature>>>,
233    watch_path: PathBuf,
234    ignore_paths: Vec<PathBuf>,
235) -> Result<()> {
236    let (tx, mut rx) = tokio::sync::mpsc::channel(100);
237
238    // Set up the file watcher in a blocking task
239    let watch_path_clone = watch_path.clone();
240    let _watcher = tokio::task::spawn_blocking(move || -> Result<RecommendedWatcher> {
241        let mut watcher = RecommendedWatcher::new(
242            move |res: notify::Result<Event>| {
243                match res {
244                    Ok(event) => {
245                        // Send event through channel
246                        if let Err(e) = tx.blocking_send(event) {
247                            eprintln!("Failed to send file system event: {}", e);
248                        }
249                    }
250                    Err(e) => eprintln!("File watcher error: {:?}", e),
251                }
252            },
253            Config::default(),
254        )?;
255
256        watcher.watch(&watch_path_clone, RecursiveMode::Recursive)?;
257        Ok(watcher)
258    })
259    .await??;
260
261    // Process file system events
262    while let Some(event) = rx.recv().await {
263        // Check if this is a file we care about (README.md files or directory changes)
264        let should_recompute = event.paths.iter().any(|path| {
265            path.file_name()
266                .map(|name| name == "README.md")
267                .unwrap_or(false)
268                || event.kind.is_create()
269                || event.kind.is_remove()
270        });
271
272        if should_recompute {
273            // Add a small delay to avoid excessive recomputation during rapid changes
274            sleep(Duration::from_millis(500)).await;
275
276            match list_files_recursive_with_changes(&watch_path, &ignore_paths) {
277                Ok(new_features) => {
278                    let mut features = features_data.write().await;
279                    *features = new_features;
280                    println!("✅ Features updated successfully");
281                }
282                Err(e) => {
283                    eprintln!("❌ Failed to recompute features: {}", e);
284                }
285            }
286        }
287    }
288
289    Ok(())
290}
291
292/// Custom error type for serialization failures
293#[derive(Debug)]
294struct SerializationError;
295impl warp::reject::Reject for SerializationError {}
296
297/// Serves the index page for the root path.
298///
299/// If embedded `index.html` exists, it will be served. Otherwise, a default
300/// HTML page with navigation links will be returned.
301///
302/// # Returns
303///
304/// * `Result<impl warp::Reply, warp::Rejection>` - HTML response or rejection
305async fn serve_index() -> Result<impl warp::Reply, warp::Rejection> {
306    if let Some(file) = STATIC_DIR.get_file("index.html") {
307        let content = file.contents_utf8().unwrap_or("");
308        Ok(
309            warp::reply::with_header(content, "content-type", "text/html; charset=utf-8")
310                .into_response(),
311        )
312    } else {
313        let html = create_default_index_html();
314        Ok(
315            warp::reply::with_header(html, "content-type", "text/html; charset=utf-8")
316                .into_response(),
317        )
318    }
319}
320
321/// Serves static files from the embedded directory.
322///
323/// # Arguments
324///
325/// * `path` - The requested file path
326///
327/// # Returns
328///
329/// * `Result<impl warp::Reply, warp::Rejection>` - File content or rejection
330async fn serve_static_file(path: warp::path::Tail) -> Result<impl warp::Reply, warp::Rejection> {
331    let path_str = path.as_str();
332
333    // Try to get the file from the embedded directory
334    if let Some(file) = STATIC_DIR.get_file(path_str) {
335        let content_type = get_content_type(path_str);
336
337        if let Some(contents) = file.contents_utf8() {
338            // Text file
339            Ok(warp::reply::with_header(contents, "content-type", content_type).into_response())
340        } else {
341            // Binary file
342            Ok(
343                warp::reply::with_header(file.contents(), "content-type", content_type)
344                    .into_response(),
345            )
346        }
347    } else {
348        Err(warp::reject::not_found())
349    }
350}
351
352/// Determines the content type based on file extension.
353///
354/// # Arguments
355///
356/// * `path` - The file path
357///
358/// # Returns
359///
360/// * `&'static str` - The appropriate MIME type
361fn get_content_type(path: &str) -> &'static str {
362    let extension = Path::new(path)
363        .extension()
364        .and_then(|ext| ext.to_str())
365        .unwrap_or("");
366
367    match extension.to_lowercase().as_str() {
368        "html" => "text/html; charset=utf-8",
369        "css" => "text/css; charset=utf-8",
370        "js" => "application/javascript; charset=utf-8",
371        "json" => "application/json; charset=utf-8",
372        "svg" => "image/svg+xml",
373        "png" => "image/png",
374        "jpg" | "jpeg" => "image/jpeg",
375        "gif" => "image/gif",
376        "ico" => "image/x-icon",
377        "txt" => "text/plain; charset=utf-8",
378        "pdf" => "application/pdf",
379        "xml" => "application/xml; charset=utf-8",
380        "woff" => "font/woff",
381        "woff2" => "font/woff2",
382        "ttf" => "font/ttf",
383        "eot" => "application/vnd.ms-fontobject",
384        _ => "application/octet-stream",
385    }
386}
387
388/// Creates the default HTML page when no index.html is found.
389fn create_default_index_html() -> String {
390    r#"<!DOCTYPE html>
391<html lang="en">
392<head>
393    <meta charset="UTF-8">
394    <meta name="viewport" content="width=device-width, initial-scale=1.0">
395    <title>Features Dashboard</title>
396    <style>
397        body {
398            font-family: Arial, sans-serif;
399            margin: 40px;
400            line-height: 1.6;
401            background: #f5f5f5;
402        }
403        .container {
404            max-width: 800px;
405            margin: 0 auto;
406            background: white;
407            padding: 30px;
408            border-radius: 8px;
409            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
410        }
411        h1 { color: #333; }
412        .links { list-style: none; padding: 0; }
413        .links li { margin: 10px 0; }
414        .links a {
415            color: #007acc;
416            text-decoration: none;
417            padding: 8px 15px;
418            border: 1px solid #007acc;
419            border-radius: 4px;
420            display: inline-block;
421        }
422        .links a:hover { background: #007acc; color: white; }
423    </style>
424</head>
425<body>
426    <div class="container">
427        <h1>đŸ—ī¸ Features Dashboard</h1>
428        <p>Welcome to the feature-based architecture server!</p>
429        <ul class="links">
430            <li><a href="/features.json">📊 View Features JSON</a></li>
431            <li><a href="/metadata.json">â„šī¸ View Metadata JSON</a></li>
432        </ul>
433        <p><small>This server provides features data and serves embedded static files from the binary.</small></p>
434    </div>
435</body>
436</html>"#.to_string()
437}
438
439/// Handles HTTP request rejections and converts them to appropriate responses.
440async fn handle_rejection(
441    err: warp::Rejection,
442) -> Result<impl warp::Reply, std::convert::Infallible> {
443    let code;
444    let message;
445
446    if err.is_not_found() {
447        code = warp::http::StatusCode::NOT_FOUND;
448        message = "NOT_FOUND";
449    } else if err
450        .find::<warp::filters::body::BodyDeserializeError>()
451        .is_some()
452    {
453        code = warp::http::StatusCode::BAD_REQUEST;
454        message = "BAD_REQUEST";
455    } else if err.find::<warp::reject::MethodNotAllowed>().is_some() {
456        code = warp::http::StatusCode::METHOD_NOT_ALLOWED;
457        message = "METHOD_NOT_ALLOWED";
458    } else {
459        eprintln!("Unhandled rejection: {:?}", err);
460        code = warp::http::StatusCode::INTERNAL_SERVER_ERROR;
461        message = "INTERNAL_SERVER_ERROR";
462    }
463
464    Ok(warp::reply::with_status(message, code))
465}