lyrs/src/main.rs

96 lines
2.8 KiB
Rust
Raw Normal View History

2024-05-06 15:39:21 -05:00
use axum::{serve, Router};
use notify::{Config, RecommendedWatcher, RecursiveMode, Watcher};
use std::{
path::{Path, PathBuf},
str::FromStr,
2024-05-06 15:39:21 -05:00
sync::OnceLock,
};
use tokio::sync::mpsc::channel;
2024-05-06 15:39:21 -05:00
use tower_http::services::ServeDir;
use tower_livereload::{LiveReloadLayer, Reloader};
pub use tracing::{debug, error, info, warn};
2024-05-06 15:39:21 -05:00
type Berr = Box<dyn std::error::Error>;
type Besult<T> = Result<T, Berr>;
2024-05-06 13:05:04 -05:00
mod observe {
pub fn setup_logging() {
color_eyre::install().expect("Failed to install color_eyre");
2024-05-06 15:39:21 -05:00
let filter = tracing_subscriber::EnvFilter::builder()
.with_default_directive(<tracing_subscriber::filter::Directive>::from(
tracing::level_filters::LevelFilter::TRACE,
))
.parse_lossy("info,lyrs=trace");
2024-05-06 13:05:04 -05:00
tracing_subscriber::fmt().with_env_filter(filter).init();
}
}
2024-05-06 15:39:21 -05:00
fn static_file_dir() -> &'static PathBuf {
static STATIC_FILE_DIR: OnceLock<PathBuf> = OnceLock::new();
STATIC_FILE_DIR.get_or_init(|| PathBuf::from_str("static").unwrap())
2024-05-06 13:05:04 -05:00
}
2024-05-06 15:39:21 -05:00
#[tokio::main]
async fn main() -> Besult<()> {
// load configuration?
observe::setup_logging();
2024-05-06 15:39:21 -05:00
let rl_layer = live_reload_layer()?;
2024-05-06 15:39:21 -05:00
let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
info!("Listening on {listener:#?}");
Ok(serve(listener, static_files()?.layer(rl_layer)).await?)
}
2024-05-06 15:39:21 -05:00
fn live_reload_layer() -> Besult<LiveReloadLayer> {
let rl_layer = LiveReloadLayer::new();
let rl = rl_layer.reloader();
static_file_watcher(rl)?;
Ok(rl_layer)
}
2024-05-06 15:39:21 -05:00
fn static_file_watcher(reloader: Reloader) -> Result<(), Box<dyn std::error::Error>> {
info!("Creating async watcher...");
let (tx, mut rx) = channel(1);
info!("Creating watcher...");
let mut watcher = RecommendedWatcher::new(
move |res| {
info!("Res from watcher: {res:#?}");
futures::executor::block_on(async {
tx.send(res).await.unwrap();
})
},
Config::default(),
)?;
info!("Created watcher");
watcher.watch(static_file_dir(), RecursiveMode::Recursive)?;
tokio::spawn(async move {
info!("Recieving...");
while let Some(res) = rx.recv().await {
info!("Recieved! {res:#?}");
match res {
Ok(event) => {
info!("fs event: {event:#?}");
2024-05-06 15:39:21 -05:00
reloader.reload()
}
Err(e) => println!("watch error: {:?}", e),
}
}
});
2024-05-06 15:39:21 -05:00
Ok(())
}
fn static_files() -> Result<Router, notify::Error> {
let static_file_path = Path::new("./static/");
// serve the file in the "assets" directory under `/assets`
info!("Starting static file server...");
Ok(Router::new().nest_service("/static", ServeDir::new(static_file_path)))
2024-05-05 09:47:13 -05:00
}