From 256163db6cf4d822d0144c97c590842d2693e52b Mon Sep 17 00:00:00 2001 From: Kieran Moy Date: Mon, 5 Aug 2024 20:10:29 +0800 Subject: [PATCH] add anyhow --- Cargo.lock | 1 + Cargo.toml | 1 + src/config.rs | 28 ++++++++++++++++++---------- src/init.rs | 16 ++++++++-------- src/route.rs | 29 +++++++++++------------------ src/zest.rs | 17 ++++++++++------- 6 files changed, 49 insertions(+), 43 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 51c3438..f493c41 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1148,6 +1148,7 @@ dependencies = [ name = "zest" version = "0.1.9" dependencies = [ + "anyhow", "async-mutex", "async-rwlock", "chrono", diff --git a/Cargo.toml b/Cargo.toml index 89e7721..ed70b85 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -17,6 +17,7 @@ ip_limit = ["dep:ipnet"] log = ["dep:log"] [dependencies] +anyhow = "1.0.86" async-mutex = "1.4.0" async-rwlock = "1.3.0" chrono = { version = "0.4.38", features = ["clock", "now"] } diff --git a/src/config.rs b/src/config.rs index 6189ebe..1d799e7 100644 --- a/src/config.rs +++ b/src/config.rs @@ -3,7 +3,22 @@ use clap::{command, Parser}; use lazy_static::lazy_static; use serde::{Deserialize, Serialize}; use serde_yml::Value; -use std::{collections::HashMap, env::current_dir, fs, path::PathBuf, sync::{Arc, Mutex}, time::Duration}; +use std::{ + collections::HashMap, + env::current_dir, + fs, + path::PathBuf, + sync::{Arc, Mutex}, + time::Duration, +}; + +lazy_static! { + pub static ref CONFIG_PATH: Mutex = Mutex::new("".to_owned()); + pub static ref DEFAULT_CONFIG: Config = init_config(); + pub static ref CONFIG: Arc> = Arc::new(RwLock::new((*DEFAULT_CONFIG).clone())); + pub static ref ARGS: Args = Args::parse(); + pub static ref DEFAULT_TICK: Duration = Duration::from_millis(1024); +} #[derive(Serialize, Deserialize, Clone)] pub struct Config { @@ -27,8 +42,8 @@ impl Default for Config { info: "Powered by Rust".to_owned(), root: current_dir().unwrap_or(".".into()), error_page: Some("404.html".to_owned().into()), - tick: None, - cache: None, + tick: Some(*DEFAULT_TICK), + cache: Some(CacheConfig::default()), }, allowlist: None, blocklist: None, @@ -99,13 +114,6 @@ pub struct Args { pub port: Option, } -lazy_static! { - pub static ref CONFIG_PATH: Mutex = Mutex::new("".to_owned()); - pub static ref DEFAULT_CONFIG: Config = init_config(); - pub static ref CONFIG: Arc> = Arc::new(RwLock::new((*DEFAULT_CONFIG).clone())); - pub static ref ARGS: Args = Args::parse(); -} - pub fn init_config() -> Config { let config_path = CONFIG_PATH.lock().unwrap(); let default_config = Config::default(); diff --git a/src/init.rs b/src/init.rs index 2a619c0..df9b22e 100644 --- a/src/init.rs +++ b/src/init.rs @@ -1,13 +1,12 @@ -use crate::config::{init_config, CONFIG, DEFAULT_CONFIG}; +use crate::config::{init_config, CONFIG, DEFAULT_CONFIG, DEFAULT_TICK}; +use anyhow::Result; use async_mutex::Mutex; use async_rwlock::RwLock; use lazy_static::lazy_static; use log4rs::Handle; use lru::LruCache; use signal_hook::{consts::SIGHUP, iterator::Signals}; -use std::{ - env::set_current_dir, error::Error, io, num::NonZeroUsize, sync::Arc, thread, time::Duration, -}; +use std::{env::set_current_dir, error::Error, io, num::NonZeroUsize, sync::Arc, thread}; #[cfg(feature = "log")] use { @@ -22,7 +21,6 @@ use { lazy_static! { pub static ref T: Arc>> = Arc::new(RwLock::new(None)); - pub static ref DEFAULT_TICK: Duration = Duration::from_millis(1024); pub static ref LOGGER_HANDLE: Mutex> = Mutex::new(None); } @@ -137,15 +135,17 @@ where } #[cfg(feature = "log")] -pub async fn init_logger(config: C) +pub async fn init_logger(config: C) -> Result<(), log::SetLoggerError> where C: Deref, { let config = build_logger_config(config).await; - *LOGGER_HANDLE.lock().await = Some(log4rs::init_config(config).unwrap()) + *LOGGER_HANDLE.lock().await = Some(log4rs::init_config(config)?); + + Ok(()) } -pub async fn init_signal() -> Result<(), Box> { +pub async fn init_signal() -> io::Result<()> { let mut signals = Signals::new([SIGHUP])?; tokio::spawn(async move { diff --git a/src/route.rs b/src/route.rs index a09077e..880005f 100644 --- a/src/route.rs +++ b/src/route.rs @@ -1,8 +1,8 @@ use crate::config::{LocationConfig, CONFIG}; +use anyhow::{anyhow, Context, Result}; use serde_yml::from_value; use std::{ fmt::Write, - io::{ErrorKind, Result}, path::{Path, PathBuf}, }; use tokio::fs::{self, read_dir, DirEntry}; @@ -18,23 +18,16 @@ pub async fn location_index(path: PathBuf, location: &str) -> Result { for (s, v) in &config.locations.clone().unwrap_or_default() { if root_relative(s) == location.trim_end_matches('/') { - match from_value::(v.clone()) { - Ok(_location) => { - if let Some(index) = _location.index { - return fs::read_to_string(root_relative( - PathBuf::from(location) - .join(index.clone()) - .as_path() - .to_str() - .unwrap(), - )) - .await; - } else if _location.auto_index.is_none() || !_location.auto_index.unwrap() { - return Err(ErrorKind::Unsupported.into()); - } - } - _ => { - continue; + if let Ok(_location) = from_value::(v.clone()) { + if let Some(index) = _location.index { + let path = PathBuf::from(location).join(index.clone()); + let _path = root_relative(path.as_path().to_str().unwrap()); + + return fs::read_to_string(_path) + .await + .with_context(move || format!("failed to read path {}", _path)); + } else if _location.auto_index.is_none() || !_location.auto_index.unwrap() { + return Err(anyhow!("Index not supported")); } } } diff --git a/src/zest.rs b/src/zest.rs index e409c50..4652d29 100644 --- a/src/zest.rs +++ b/src/zest.rs @@ -1,13 +1,14 @@ use crate::{ - config::{Config, ARGS, CONFIG, CONFIG_PATH, DEFAULT_CONFIG}, - init::{init_cache, init_signal, DATE_FORMAT, DEFAULT_TICK, FILE_CACHE, INDEX_CACHE, T}, + config::{Config, ARGS, CONFIG, CONFIG_PATH, DEFAULT_CONFIG, DEFAULT_TICK}, + init::{init_cache, init_signal, DATE_FORMAT, FILE_CACHE, INDEX_CACHE, T}, route::{location_index, mime_match, root_relative, status_page}, }; +use anyhow::{Context, Result}; use chrono::{DateTime, Utc}; use mime::Mime; use std::{ - collections::HashMap, env::set_current_dir, error::Error, io, ops::Deref, path::Path, sync::Arc, + collections::HashMap, env::set_current_dir, error::Error, ops::Deref, path::Path, sync::Arc, }; #[cfg(feature = "log")] @@ -67,7 +68,7 @@ impl<'a> Response<'a> { } } -async fn handle_connection(mut stream: S) -> io::Result<(i32, String)> +async fn handle_connection(mut stream: S) -> Result<(i32, String)> where S: AsyncReadExt + AsyncWriteExt + Unpin, { @@ -305,12 +306,14 @@ pub async fn zest_main() -> Result<(), Box> { set_current_dir(config.clone().server.root)?; #[cfg(feature = "log")] - init_logger(&config.clone()).await; + init_logger(&config.clone()) + .await + .context("failed to init logger")?; - init_signal().await.unwrap(); + init_signal().await.context("failed to init signal")?; #[cfg(feature = "lru_cache")] - init_cache().await.unwrap(); + init_cache().await.context("failed to init lru cache")?; loop { let _config = CONFIG.try_read().unwrap();