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::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
26// Embed the public directory at compile time
27static STATIC_DIR: Dir<'_> = include_dir!("$CARGO_MANIFEST_DIR/public");
28
29/// Configuration for the HTTP server
30#[derive(Debug, Clone)]
31pub struct ServerConfig {
32    /// Port to run the server on
33    pub port: u16,
34    /// Host address to bind to
35    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    /// Create a new server configuration with custom port
49    pub fn new(port: u16) -> Self {
50        Self {
51            port,
52            ..Default::default()
53        }
54    }
55
56    /// Set the host address to bind to
57    #[allow(dead_code)]
58    pub fn with_host(mut self, host: [u8; 4]) -> Self {
59        self.host = host;
60        self
61    }
62}
63
64/// Starts an HTTP server with file watching for a specific directory.
65///
66/// # Arguments
67///
68/// * `features` - Initial Feature objects to serve as JSON
69/// * `port` - Port number to run the server on
70/// * `watch_path` - Path to watch for file changes
71/// * `on_ready` - Optional callback to be called when server is ready
72/// * `skip_changes` - Whether changes were skipped during feature computation
73/// * `ignore_paths` - Folders to ignore when features are recomputed
74/// * `include_skipped_dirs` - Whether to scan folders skipped by default when features are recomputed
75///
76/// # Returns
77///
78/// * `Result<()>` - Ok if server starts successfully, Err otherwise
79pub 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
101/// Starts an HTTP server with custom configuration and optional file watching.
102///
103/// # Arguments
104///
105/// * `features` - Slice of Feature objects to serve as JSON
106/// * `config` - Server configuration
107/// * `watch_path` - Optional path to watch for file changes
108/// * `on_ready` - Optional callback to be called when server is ready
109/// * `skip_changes` - Whether changes were skipped during feature computation
110/// * `ignore_paths` - Folders to ignore when features are recomputed
111/// * `include_skipped_dirs` - Whether to scan folders skipped by default when features are recomputed
112///
113/// # Returns
114///
115/// * `Result<()>` - Ok if server starts successfully, Err otherwise
116pub 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    // Create shared state for features
126    let features_data = Arc::new(RwLock::new(features.to_vec()));
127
128    // When the features data was last built, refreshed by the file watcher
129    let built_at = Arc::new(RwLock::new(current_build_timestamp()));
130
131    // Get repository URL from git config
132    let repository_url = watch_path
133        .as_ref()
134        .and_then(|path| get_repository_url(path));
135
136    // Set up file watching if watch_path is provided
137    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    // Route for features.json with shared state
158    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    // Route for metadata.json with version info and repository URL
182    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                // Add repository URL if available
196                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    // Route for root path to serve index.html
217    let index_route = warp::path::end().and(warp::get()).and_then(serve_index);
218
219    // Route for static files from embedded directory
220    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    // Call the ready callback if provided
232    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
251/// Sets up file system watching for the specified path.
252async 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    // Set up the file watcher in a blocking task
262    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                        // Send event through channel
269                        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    // Process file system events
285    while let Some(event) = rx.recv().await {
286        // Check if this is a file we care about (README.md files or directory changes)
287        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            // Add a small delay to avoid excessive recomputation during rapid changes
297            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/// Custom error type for serialization failures
321#[derive(Debug)]
322struct SerializationError;
323impl warp::reject::Reject for SerializationError {}
324
325/// Serves the index page for the root path.
326///
327/// If embedded `index.html` exists, it will be served. Otherwise, a default
328/// HTML page with navigation links will be returned.
329///
330/// # Returns
331///
332/// * `Result<impl warp::Reply, warp::Rejection>` - HTML response or rejection
333async 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
349/// Serves static files from the embedded directory.
350///
351/// # Arguments
352///
353/// * `path` - The requested file path
354///
355/// # Returns
356///
357/// * `Result<impl warp::Reply, warp::Rejection>` - File content or rejection
358async fn serve_static_file(path: warp::path::Tail) -> Result<impl warp::Reply, warp::Rejection> {
359    let path_str = path.as_str();
360
361    // Try to get the file from the embedded directory
362    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            // Text file
367            Ok(warp::reply::with_header(contents, "content-type", content_type).into_response())
368        } else {
369            // Binary file
370            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
380/// Determines the content type based on file extension.
381///
382/// # Arguments
383///
384/// * `path` - The file path
385///
386/// # Returns
387///
388/// * `&'static str` - The appropriate MIME type
389fn 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
416/// Creates the default HTML page when no index.html is found.
417fn 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
467/// Handles HTTP request rejections and converts them to appropriate responses.
468async 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}