use anyhow::Result;
use include_dir::{Dir, include_dir};
use notify::{Config, Event, RecommendedWatcher, RecursiveMode, Watcher};
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::time::Duration;
use tokio::sync::RwLock;
use tokio::time::sleep;
use warp::{Filter, Reply};
use crate::build::current_build_timestamp;
use crate::file_scanner::list_files_recursive_with_changes;
use crate::git_helper::get_repository_url;
use crate::models::Feature;
static STATIC_DIR: Dir<'_> = include_dir!("$CARGO_MANIFEST_DIR/public");
#[derive(Debug, Clone)]
pub struct ServerConfig {
pub port: u16,
pub host: [u8; 4],
}
impl Default for ServerConfig {
fn default() -> Self {
Self {
port: 3000,
host: [127, 0, 0, 1],
}
}
}
impl ServerConfig {
pub fn new(port: u16) -> Self {
Self {
port,
..Default::default()
}
}
#[allow(dead_code)]
pub fn with_host(mut self, host: [u8; 4]) -> Self {
self.host = host;
self
}
}
pub async fn serve_features_with_watching(
features: &[Feature],
port: u16,
watch_path: PathBuf,
on_ready: Option<Box<dyn FnOnce() + Send>>,
skip_changes: bool,
ignore_paths: Vec<PathBuf>,
include_skipped_dirs: bool,
) -> Result<()> {
let config = ServerConfig::new(port);
serve_features_with_config_and_watching(
features,
config,
Some(watch_path.clone()),
on_ready,
skip_changes,
ignore_paths,
include_skipped_dirs,
)
.await
}
pub async fn serve_features_with_config_and_watching(
features: &[Feature],
config: ServerConfig,
watch_path: Option<PathBuf>,
on_ready: Option<Box<dyn FnOnce() + Send>>,
skip_changes: bool,
ignore_paths: Vec<PathBuf>,
include_skipped_dirs: bool,
) -> Result<()> {
let features_data = Arc::new(RwLock::new(features.to_vec()));
let built_at = Arc::new(RwLock::new(current_build_timestamp()));
let repository_url = watch_path
.as_ref()
.and_then(|path| get_repository_url(path));
if let Some(ref path) = watch_path {
let features_data_clone = Arc::clone(&features_data);
let built_at_clone = Arc::clone(&built_at);
let watch_path_clone = path.clone();
tokio::spawn(async move {
if let Err(e) = setup_file_watcher(
features_data_clone,
built_at_clone,
watch_path_clone,
ignore_paths,
include_skipped_dirs,
)
.await
{
eprintln!("File watcher error: {}", e);
}
});
}
let features_data_clone = Arc::clone(&features_data);
let features_route = warp::path("features.json")
.and(warp::get())
.and_then(move || {
let features_data = Arc::clone(&features_data_clone);
async move {
let features = features_data.read().await;
let features_json = match serde_json::to_string_pretty(&*features) {
Ok(json) => json,
Err(e) => {
eprintln!("Failed to serialize features: {}", e);
return Err(warp::reject::custom(SerializationError));
}
};
Ok::<_, warp::Rejection>(warp::reply::with_header(
features_json,
"content-type",
"application/json",
))
}
});
let metadata_route = warp::path("metadata.json")
.and(warp::get())
.and_then(move || {
let repo_url = repository_url.clone();
let built_at = Arc::clone(&built_at);
async move {
let built_at = built_at.read().await.clone();
let mut metadata = serde_json::json!({
"version": env!("CARGO_PKG_VERSION"),
"skipChanges": skip_changes,
"builtAt": built_at
});
if let Some(url) = repo_url {
metadata["repository"] = serde_json::json!(url);
}
let metadata_json = match serde_json::to_string_pretty(&metadata) {
Ok(json) => json,
Err(e) => {
eprintln!("Failed to serialize metadata: {}", e);
return Err(warp::reject::custom(SerializationError));
}
};
Ok::<_, warp::Rejection>(warp::reply::with_header(
metadata_json,
"content-type",
"application/json",
))
}
});
let index_route = warp::path::end().and(warp::get()).and_then(serve_index);
let static_route = warp::path::tail()
.and(warp::get())
.and_then(serve_static_file);
let routes = features_route
.or(metadata_route)
.or(index_route)
.or(static_route)
.with(warp::cors().allow_any_origin())
.recover(handle_rejection);
if let Some(callback) = on_ready {
callback();
}
println!(
"Server running at http://{}:{}",
config
.host
.iter()
.map(|&b| b.to_string())
.collect::<Vec<_>>()
.join("."),
config.port,
);
warp::serve(routes).run((config.host, config.port)).await;
Ok(())
}
async fn setup_file_watcher(
features_data: Arc<RwLock<Vec<Feature>>>,
built_at: Arc<RwLock<String>>,
watch_path: PathBuf,
ignore_paths: Vec<PathBuf>,
include_skipped_dirs: bool,
) -> Result<()> {
let (tx, mut rx) = tokio::sync::mpsc::channel(100);
let watch_path_clone = watch_path.clone();
let _watcher = tokio::task::spawn_blocking(move || -> Result<RecommendedWatcher> {
let mut watcher = RecommendedWatcher::new(
move |res: notify::Result<Event>| {
match res {
Ok(event) => {
if let Err(e) = tx.blocking_send(event) {
eprintln!("Failed to send file system event: {}", e);
}
}
Err(e) => eprintln!("File watcher error: {:?}", e),
}
},
Config::default(),
)?;
watcher.watch(&watch_path_clone, RecursiveMode::Recursive)?;
Ok(watcher)
})
.await??;
while let Some(event) = rx.recv().await {
let should_recompute = event.paths.iter().any(|path| {
path.file_name()
.map(|name| name == "README.md")
.unwrap_or(false)
|| event.kind.is_create()
|| event.kind.is_remove()
});
if should_recompute {
sleep(Duration::from_millis(500)).await;
match list_files_recursive_with_changes(
&watch_path,
&ignore_paths,
include_skipped_dirs,
) {
Ok(new_features) => {
let mut features = features_data.write().await;
*features = new_features;
*built_at.write().await = current_build_timestamp();
println!("â
Features updated successfully");
}
Err(e) => {
eprintln!("â Failed to recompute features: {}", e);
}
}
}
}
Ok(())
}
#[derive(Debug)]
struct SerializationError;
impl warp::reject::Reject for SerializationError {}
async fn serve_index() -> Result<impl warp::Reply, warp::Rejection> {
if let Some(file) = STATIC_DIR.get_file("index.html") {
let content = file.contents_utf8().unwrap_or("");
Ok(
warp::reply::with_header(content, "content-type", "text/html; charset=utf-8")
.into_response(),
)
} else {
let html = create_default_index_html();
Ok(
warp::reply::with_header(html, "content-type", "text/html; charset=utf-8")
.into_response(),
)
}
}
async fn serve_static_file(path: warp::path::Tail) -> Result<impl warp::Reply, warp::Rejection> {
let path_str = path.as_str();
if let Some(file) = STATIC_DIR.get_file(path_str) {
let content_type = get_content_type(path_str);
if let Some(contents) = file.contents_utf8() {
Ok(warp::reply::with_header(contents, "content-type", content_type).into_response())
} else {
Ok(
warp::reply::with_header(file.contents(), "content-type", content_type)
.into_response(),
)
}
} else {
Err(warp::reject::not_found())
}
}
fn get_content_type(path: &str) -> &'static str {
let extension = Path::new(path)
.extension()
.and_then(|ext| ext.to_str())
.unwrap_or("");
match extension.to_lowercase().as_str() {
"html" => "text/html; charset=utf-8",
"css" => "text/css; charset=utf-8",
"js" => "application/javascript; charset=utf-8",
"json" => "application/json; charset=utf-8",
"svg" => "image/svg+xml",
"png" => "image/png",
"jpg" | "jpeg" => "image/jpeg",
"gif" => "image/gif",
"ico" => "image/x-icon",
"txt" => "text/plain; charset=utf-8",
"pdf" => "application/pdf",
"xml" => "application/xml; charset=utf-8",
"woff" => "font/woff",
"woff2" => "font/woff2",
"ttf" => "font/ttf",
"eot" => "application/vnd.ms-fontobject",
_ => "application/octet-stream",
}
}
fn create_default_index_html() -> String {
r#"<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Features Dashboard</title>
<style>
body {
font-family: Arial, sans-serif;
margin: 40px;
line-height: 1.6;
background: #f5f5f5;
}
.container {
max-width: 800px;
margin: 0 auto;
background: white;
padding: 30px;
border-radius: 8px;
box-shadow: 0 2px 10px rgba(0,0,0,0.1);
}
h1 { color: #333; }
.links { list-style: none; padding: 0; }
.links li { margin: 10px 0; }
.links a {
color: #007acc;
text-decoration: none;
padding: 8px 15px;
border: 1px solid #007acc;
border-radius: 4px;
display: inline-block;
}
.links a:hover { background: #007acc; color: white; }
</style>
</head>
<body>
<div class="container">
<h1>đī¸ Features Dashboard</h1>
<p>Welcome to the feature-based architecture server!</p>
<ul class="links">
<li><a href="/features.json">đ View Features JSON</a></li>
<li><a href="/metadata.json">âšī¸ View Metadata JSON</a></li>
</ul>
<p><small>This server provides features data and serves embedded static files from the binary.</small></p>
</div>
</body>
</html>"#.to_string()
}
async fn handle_rejection(
err: warp::Rejection,
) -> Result<impl warp::Reply, std::convert::Infallible> {
let (code, message) = if err.is_not_found() {
(warp::http::StatusCode::NOT_FOUND, "NOT_FOUND")
} else if err
.find::<warp::filters::body::BodyDeserializeError>()
.is_some()
{
(warp::http::StatusCode::BAD_REQUEST, "BAD_REQUEST")
} else if err.find::<warp::reject::MethodNotAllowed>().is_some() {
(
warp::http::StatusCode::METHOD_NOT_ALLOWED,
"METHOD_NOT_ALLOWED",
)
} else {
eprintln!("Unhandled rejection: {:?}", err);
(
warp::http::StatusCode::INTERNAL_SERVER_ERROR,
"INTERNAL_SERVER_ERROR",
)
};
Ok(warp::reply::with_status(message, code))
}